<?php


namespace app\api\controller\xiluhouse;


use app\common\controller\Api;
use app\common\model\xiluhouse\Config;
use app\common\model\xiluhouse\UserProfile;
use think\Db;
use think\Hook;
use think\Validate;
use think\View;
use function fast\array_get;
use app\common\model\xiluhouse\RentalOrder AS RentalOrderModel;

class RentalOrder extends Api
{
    protected $noNeedLogin = ['test'];
    protected $noNeedRight = ['*'];

    /**
     * 用户签约订单列表
     */
    public function lists(){
        $state = $this->request->param('state',0);
        $q = $this->request->param('q');

        $query = RentalOrderModel::with(['rental'])
            ->where('rental_order.renter_user_id',$this->auth->id);
        if($q){
            $query->where('rental_order.order_no|rental.name','like',"%{$q}%");
        }
        switch ($state){
            case -1:
                #已取消
                $query->where('order_state',2);
                break;
            case 1:
                #待签约-两方都未签约
                $query->where('order_state',1)
                    ->where('state',1)
                    ->where('lessor_state',0);
                break;
            case 2:
                #签约中-有一方未签约
                $query->where('order_state',1)
                    ->where(function ($query){$query->where('state','1')->whereOr('lessor_state',0);});
                break;
            case 3:
                #待支付-租客和房东都签约,但是租客未支付
                $query->where('order_state',1)
                    ->where("state",2)
                    ->where('lessor_state',1)
                    ->where('pay_status',0);
                break;
            case 4:
                #已完成-已签约-租客已支付
                $query->where('order_state',3)
                    ->where('state',2)
                    ->where('lessor_state',1)
                    ->where('pay_status',1);
                break;
        }
        $lists = $query->order('updatetime','desc')
            ->paginate()->each(function ($row){
                $row->rental->append(['house_tag_text_arr']);
            });

        $this->success('查询成功',$lists);
    }
    /**
     * 用户id订单详情
     */
    public function detail(){
        $rental_order_id = $this->request->param('rental_order_id',0);
        if(!$rental_order_id){
            $this->error('参数错误');
        }
        $rental_order = RentalOrderModel::with(['rental'])
            ->order('updatetime','desc')
            ->where('rental_order.id',$rental_order_id)
            ->find();
        if($rental_order->rent_start_date){
            $rental_order->rent_start_date = date("Y-m-d",$rental_order['rent_start_date']);
        }
        if($rental_order->rent_end_date){
            $rental_order->rent_end_date = date("Y-m-d",$rental_order['rent_end_date']);
        }
        $rental_order->rental->append(['house_tag_text_arr']);
        $this->success('查询成功',$rental_order);
    }
    /**
     * 合同赋值
     */
    public function contract(){
        $rental_order_id = $this->request->param('rental_order_id',4);
        if(!$rental_order_id){
            $this->error("签约参数错误");
        }
        #1.获取信息
        $rental_order = RentalOrderModel::get($rental_order_id,['rental'=>function($query){
            $query->withField(['id','order_id','user_id']);
        }])->visible(['id','order_type','user_id','state','pay_status','lessor_state','lessor_user_id','lessor_name','lessor_mobile','lessor_identify','renter_user_id','renter_name','renter_mobile','renter_identify','type','deposit','unit_price','renter_money','lessor_medium_money','renter_medium_money','renter_pay_money','rent_start_date','rent_end_date','rent_address','order_state','rental','lessor_sign','renter_sign']);
        if(!$rental_order){
            $this->error('签约合同不存在');
        }
        #2.权限校验
        $profile = UserProfile::get(['user_id'=>$this->auth->id]);
        if(!$profile){
            $this->error("用户账户不存在");
        }
        $is_agent = 0; // 0租客签约,1房东签约,2=代理人
        if($profile->is_broker ==  0){
            if($rental_order->renter_user_id > 0 && $rental_order->renter_user_id !== $profile->user_id){
                $this->error("合同已被其他租客签约，不可查看");
            }
            if($rental_order->rental->user_id == $profile->user_id){
                $is_agent = 1; //房东签约
            }
        }else if($profile->is_broker ==  1){
            if($rental_order->user_id != $profile->user_id
                && ($rental_order->lessor_user_id > 0 && $rental_order->lessor_user_id != $profile->user_id)
                && ($rental_order->renter_user_id > 0 && $rental_order->renter_user_id != $profile->user_id)){
                $this->error("当前合同您不可操作");
            }
            if($rental_order->rental->user_id == $profile->user_id){
                $is_agent = 1; //房东签约
            }
        }else{
            if($rental_order->user_id !== $profile->user_id
               // && $rental_order->lessor_user_id == 2
                && ($rental_order->lessor_user_id && $rental_order->lessor_user_id !== $profile->user_id)){
                $this->error("你不是当前签约发起人或房东，不可查看");
            }
            if($rental_order->order_type == 'agent' && $rental_order->user_id == $profile->user_id){
                $is_agent = 2;
            }else{
                $is_agent = 1;
            }
        }
        #3.获取合同-配置合同模板
        $contract_id = Config::getdatas("contract_article_id");
        if(!$contract_id){
            $this->error("合同模板不存在");
        }
        $contract = \app\common\model\xiluhouse\Article::field("content")->where('id',$contract_id)->find();
        if(!$contract){
            $this->error("未找到合同");
        }

        $zuqi = floor(($rental_order['rent_end_date'] - $rental_order['rent_start_date'])/(86400*30)).'月';
        $contract_template = [
            '{1}'   =>  $rental_order['rent_address'],
            '{2}'   =>  $rental_order['unit_price'],
            '{3}'   =>  $rental_order['deposit'],
            '{4}'   =>  $rental_order['type'],
            '{5}'   =>  date("Y-m-d",$rental_order['rent_start_date']),
            '{6}'   =>  date("Y-m-d",$rental_order['rent_end_date']),
            '{7}'   =>  $zuqi,
        ];

        #4.匹配模板中要替换的变量
        $count = preg_match_all("/\{\d+\}/",$contract['content'],$column);
        $column = array_unique($column[0]);

        #5.循环替换,生成合同
        if($count>0){
            foreach ($column as $k => $v){
                $contract['content'] = str_replace($v,$contract_template[$v],$contract['content']);
            }
        }

        $this->success('查询成功',['is_agent'=>$is_agent,'contact'=>$contract,'rental_order'=>$rental_order ?? [],'profile'=>$profile]);
    }

    //合同生成pdf图片
    private function getContract($rental_order_id=216){
        $this->view    = View::instance(\think\Config::get('template'), Config::get('view_replace_str'));
        #1.获取合同
        $contract_id = Config::getdatas("contract_article_id");
        $contract = \app\common\model\xiluhouse\Article::field("content")->where('id',$contract_id)->find();

        if(!$rental_order_id){
            $this->error('签约单号错误');
        }
        #2.获取信息
        $rental_order = RentalOrderModel::get($rental_order_id,['rental'=>function($query){
            $query->withField(['id','order_id','user_id']);
        }])->visible(['id','order_type','user_id','state','pay_status','lessor_state','lessor_user_id','lessor_name','lessor_mobile','lessor_identify','renter_user_id','renter_name','renter_mobile','renter_identify','type','deposit','unit_price','renter_money','lessor_medium_money','renter_medium_money','renter_pay_money','rent_start_date','rent_end_date','rent_address','order_state','rental']);
        if(!$rental_order){
            $this->error('签约合同不存在');
        }
        #2.配置合同模板
        $zuqi = floor(($rental_order['rent_end_date'] - $rental_order['rent_start_date'])/(86400*30)).'月';
        $contract_template = [
            '{1}'   =>  $rental_order['rent_address'],
            '{2}'   =>  $rental_order['unit_price'],
            '{3}'   =>  $rental_order['deposit'],
            '{4}'   =>  $rental_order['type'],
            '{5}'   =>  date("Y-m-d",$rental_order['rent_start_date']),
            '{6}'   =>  date("Y-m-d",$rental_order['rent_end_date']),
            '{7}'   =>  $zuqi,
        ];
        #4.匹配模板中要替换的变量
        $count = preg_match_all("/\{\d+\}/",$contract['content'],$column);
        $column = array_unique($column[0]);

        #5.循环替换,生成合同
        if($count>0){
            foreach ($column as $k => $v){
                $contract['content'] = str_replace($v,$contract_template[$v],$contract['content']);
            }
        }
        $this->view->assign('contract',$contract);
        $this->view->assign('rental_order',$rental_order);
        $mpdf = new \Mpdf\Mpdf([
            'mode' => 'UTF-8', 'format' => 'A4', 'default_font_size' => 40, 'default_font' => '', 'margin_left' => 20, 'margin_right' => 20

        ]);
        $mpdf->autoScriptToLang = true;//支持中文设置

        $mpdf->autoLangToFont = true;//支持中文设置
        $html = $this->view->fetch("contact");
        $filename = md5(mt_rand()).'.pdf';
        $path = "/xiaoxiong/".date('Ymd').'/';

        if (!file_exists('.' . $path)) {
            @mkdir('.' . $path, 0777, true);
        }
        $concat_image = $path.$filename;
        $mpdf->WriteHTML($html);
        $mpdf->Output('.'.$concat_image,'f');
        return request()->domain().$concat_image;
    }
    /**
     * 租客-房东签约
     */
    public function user_sign(){
        #更新租客信息合同与签名
        $params = $this->request->param('');
        $rental_order_id = array_get($params,'rental_order_id');
        if(!$rental_order_id){
            $this->error('参数错误');
        }
        $rental_order = RentalOrderModel::get($rental_order_id);
        if(!$rental_order || !in_array($rental_order->checkinfo,[0,1,2])){
            $this->error('订单不存在或当前不可支付');
        }
        $userProfile = UserProfile::where('user_id',$this->auth->id)->find();
        $is_broker = array_get($params,'is_broker');
        Db::startTrans();
        if(in_array($is_broker,[1,2])){
            #房东签约
            if(!in_array($userProfile->is_broker,[1,2])){
                $this->error('不是房东或经纪人不可签约');
            }
            if($this->auth->id != $rental_order->rental->user_id){
                $this->error('非当前房源房东不可签约');
            }
            if($rental_order->lessor_state == 1){
                $this->error('房东已签约');
            }
            $params['lessor_user_id'] = $this->auth->id;
            $validate = new Validate([
                'lessor_name|房东姓名'          => 'require',
                'lessor_mobile|房东手机号'      => 'require',
                'lessor_identify|房东身份证'    => 'require',
                //'lessor_concat_image|合同'     => 'require',
                //'lessor_sign|房东签名'          => 'require',
            ]);
            if(!$validate->check($params)){
                Db::rollback();
                $this->error($validate->getError());
            }
            $params['lessor_state'] = 1; //房东已签约
            if($rental_order->state == '2' && $rental_order->pay_status == 1){
                //判断租客如果已签约则签约完成
                $params['order_state'] = 3;
                //$params['order_contract_image'] = $params['lessor_concat_image'];
                //$params['finish_time'] = time();
            }
            $params['lessor_sign_time'] = time();
        }else{
            #租客签约
            if($userProfile->is_broker == 3){
                $this->error('经纪人身份不可签约');
            }
            if($rental_order->renter_user_id &&  $rental_order->renter_user_id != $this->auth->id){
                $this->error('非当前合同签约用户');
            }
            if($rental_order->state == 2){
                $this->error('租客已签约');
            }
            $params['renter_user_id'] = $this->auth->id;
            $validate = new Validate([
                'renter_name|租客姓名'          => 'require',
                'renter_mobile|租客手机号'      => 'require',
                'renter_identify|租客身份证'    => 'require',
                //'renter_concat_image|合同'     => 'require',
                //'renter_sign|租客签名'          => 'require',
            ]);
            if(!$validate->check($params)){
                Db::rollback();
                $this->error($validate->getError());
            }
            $params['state'] = 2;
            $params['rental_sign_time'] = time();
            #支付按钮如果关闭，则租户签约完成，当前订单已完成
            $renter_pay_switch = \app\common\model\xiluhouse\Config::getdatas('renter_pay_switch') ?? 0;
            if(!$renter_pay_switch){
                #支付关闭，则直接到已完成
                $params['pay_status'] = '1';
                //$params['renter_pay_time'] = time();
                if($rental_order->lessor_state == '1'){
                    //判断房东如果已签约则签约完成
                    $params['order_state'] = 3;
                    $params['order_contract_image'] = $rental_order['renter_concat_image'];
                    $params['finish_time'] = time();
                }
            }
        }
        $rental_order->allowField(true)->save($params);
        #获取合同图片
        $contract_image = $this->getContract($rental_order->id);
        $field = in_array($is_broker,[1,2]) ? 'lessor_concat_image' : 'renter_concat_image';
        $rental_order->$field = $contract_image;

        if(in_array($is_broker,[1,2]) && $rental_order->state == '2' && $rental_order->pay_status == 1){
            $rental_order->order_contract_image = $contract_image;
            $rental_order->finish_time = time();
        }else if($is_broker == 0 && $rental_order->lessor_state == '1' && $rental_order->pay_status == 1){
            $rental_order->order_contract_image = $contract_image;
            $rental_order->finish_time = time();
        }

        if(in_array($is_broker,[1,2]) && $rental_order->lessor_state == 1 && $rental_order->pay_status == 0 && $rental_order->renter_user_id){
            $params = [
                'model_type'    =>  1,
                'user_id'       =>  $rental_order->renter_user_id,
                'title'         =>  '支付提醒',
                'order_no'      =>  $rental_order->order_no,
                'order_id'      =>  $rental_order->id
            ];
            Hook::listen("message_log",$params);
        }
        if($rental_order->lessor_state == 1 && $rental_order->pay_status == 1){
            #增加成交量
            \app\common\model\xiluhouse\UserProfile::where('user_id',$rental_order->user_id)->setInc('deal_num',1);
        }
        $rental_order->save();
        Db::commit();
        $this->success('签约成功',$rental_order);
    }

    /**
     * 用户取消签约
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function cancel(){
        $rental_order_id = $this->request->param('rental_order_id');
        if(!$rental_order_id){
            $this->error('参数错误');
        }
        $rental_order = \app\common\model\xiluhouse\RentalOrder::where('id',$rental_order_id)->find();
        if(!$rental_order || $rental_order->order_state == 2){
            $this->error('当前订单不存在或已取消');
        }
        if(!in_array($rental_order->checkinfo,[0,1,2,3])){
            $this->error('当前状态不可取消');
        }
        if($rental_order->renter_user_id != $this->auth->id){
            $this->error('没有权限');
        }
        $rental_order->state = '-1';
        $rental_order->order_state = '2';
        $rental_order->canceltime = time();
        $rental_order->save();
        $this->success('取消签约成功');
    }


    /**
     * 角标
     */
    public function sign_state_bubble(){

        #已取消
        $cancel_count = \app\common\model\xiluhouse\RentalOrder::with(['rental'])
            ->where('rental_order.user_id|rental_order.lessor_user_id',$this->auth->id)->where('order_state',2)->count('rental_order.id');
        #待签约-两方都未签约
        $unsign_count = \app\common\model\xiluhouse\RentalOrder::with(['rental'])
            ->where('rental_order.user_id|rental_order.lessor_user_id',$this->auth->id)
            ->where('order_state',1)
            ->where('state',1)
            ->where('lessor_state',0)
            ->count('rental_order.id');
        #签约中-有一方未签约
        $signing_count = \app\common\model\xiluhouse\RentalOrder::with(['rental'])
            ->where('rental_order.user_id|rental_order.lessor_user_id',$this->auth->id)
            ->where('order_state',1)
            ->where(function ($query){$query->where('state = 2 AND lessor_state = 0')->whereOr('state=1 AND lessor_state=1');})->count('rental_order.id');
        #待支付-租客和房东都签约,但是租客未支付
        $unpaid_count = \app\common\model\xiluhouse\RentalOrder::with(['rental'])
            ->where('rental_order.user_id|rental_order.lessor_user_id',$this->auth->id)
            ->where('order_state',1)
            ->where("state",1)
            ->where('lessor_state',1)
            ->where('pay_status',0)
            ->count('rental_order.id');
        #已完成-已签约-租客已支付
        $sign_finish_count = \app\common\model\xiluhouse\RentalOrder::with(['rental'])
            ->where('rental_order.user_id|rental_order.lessor_user_id',$this->auth->id)
            ->where('order_state',3)
            ->where('state',2)
            ->where('lessor_state',1)
            ->where('pay_status',1)
            ->count('rental_order.id');
        $this->success('查询成功',[
            'cancel_count'=>$cancel_count,
            'unsign_count'=>$unsign_count,
            'signing_count'=>$signing_count,
            'unpaid_count'=>$unpaid_count,
            'sign_finish_count'=>$sign_finish_count,
        ]);
    }
}